# Project: From Home Base to Swing States: The Evolution of Digital Advertising 
#          Strategies during the 2020 US Presidential Primary
# Authors: NaLette Brodnax and Piotr Sapiezynski

library(tidyverse)
library(stargazer)

ads <- read_csv('replication_data_weekly.csv')

# Fit by month (simple with no random slopes and no interactions)
mod_simple <- function(df, wk){
  data <- filter(df, week == wk)
  fit <- lm(budget_frac_per_resident ~ is_home + swing + feb + march,         
            data = data)
  return(fit)
} 

# Weeks to fit: Jan 1 thru March 3 (9 weeks)
weeks <- seq(1,9,1)
all_fits <- lapply(weeks, function(x) mod_simple(ads, x))

# Convert results to dataframe
out <- lapply(all_fits, function(x) tidy(x)) %>% 
  bind_rows()

w = NULL
for (i in weeks){
  w = c(w, rep(i,5))
}

week_data = tibble(week = w)

# Export data for plots
out_coef <- out %>% 
  bind_cols(week_data) %>% 
  filter(term %in% c('feb', 'march'))

# Plots
ggplot(aes(week, estimate, group=term), data=out_coef) + geom_line() + 
  geom_point() + geom_errorbar(aes(ymin=estimate-std.error, ymax=estimate+std.error), 
                               width=.1) + 
  facet_wrap(vars(term), ncol = 1, nrow=2, scales = 'free_y') +
  scale_x_continuous(breaks = seq(1,9,1))
